|
|
|
|
|
|
|
Visual Basic 5 allows for the use of nested SELECT queries. These are often referred to as SQL subqueries and are literally queries contained within queries. Nested SELECT queries can prove to be useful when you want to perform a query based upon the results of another query. |
|
|
|
|
|
|
|
|
To demonstrate the use of a SQL subquery, let's start Visdata and open the SUBQRY.MDB database that can be found in the \\TYSDBVB5\SOURCE\DATA directory of the CD that shipped with this book. This database contains a sample listing of authors, publishers, and book sales activity (notice that this database is very similar to the BOOKS5.MDB database) for a fictitious publisher. Our goal in this exercise is to extract the phone numbers of all the authors who sold more than 500 books in the first quarter. |
|
|
|
|
|
|
|
|
As you examine the table structure of this database in Visdata, you notice the BookSales table contains the sales records by quarter, but the phone number is contained in the Authors table. We therefore need to query the BookSales table to find all the authors who sold more than 500 books in the first quarter, and then use that result set to find the writers' phone numbers in the Authors table. We need to build a nested SELECT query. |
|
|
|
|
|
|
|
|
To do this, enter the following code into the SQL Statement window of Visdata. Execute your statement. The result set should look similar to Figure 8.35. |
|
|
|
|
|
|
|
|
SELECT * FROM Authors WHERE AUID IN (SELECT AUID
FROM Booksales WHERE Sales>500 AND Qtr=1) |
|
|
|
|
|
|
|
|
Figure 8.35.
The results of an SQL subquery. |
|
|
|
|
|
|
|
|
An SQL subquery has three main componentsthe comparison, the expression, and the SQL statement. The comparison in our example is the SELECT FROM Authors query. The expression is the IN keyword. The SQL statement is the SELECT statement within the parentheses. |
|
|
|
|
|